package com.kanesoft.android.gdx.control.input;

import com.badlogic.gdx.math.Vector2;
import com.kanesoft.android.gdx.control.input.TouchGesturesController.GestureAngle;

public class TouchVectors {

    public GestureAngle angle;
    public float angleInDegrees;
    public float intensity;
    
    public TouchVectors(GestureAngle angle, float minimumIntensity) {
        this.angle = angle;
        this.intensity = minimumIntensity;
    }

    public TouchVectors(Vector2 initialPoint, Vector2 endPoint) {
        float minX = Math.min(initialPoint.x, endPoint.x);
        float minY = Math.min(initialPoint.y, endPoint.y);
        
        float x0 = initialPoint.x - minX;
        float y0 = initialPoint.y - minY;
        float x1 = endPoint.x - minX;
        float y1 = endPoint.y - minY;

        float deltaX = x1 - x0;
        float deltaY = y1 - y0;

        intensity = (float) Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));

        if (deltaX == 0) deltaX = 0.001f;
        float atang = (deltaY / deltaX);
        
        if (deltaX != 0) {
            angleInDegrees = (float)  Math.toDegrees( Math.atan(atang));
        } else {
            angleInDegrees = 0;
        }


        if ((deltaX > 0) && (deltaY >= 0)) {
            angleInDegrees = -angleInDegrees;
            
        }

        if ((deltaX < 0) && (deltaY >= 0)) {
            angleInDegrees = 180 - angleInDegrees;
        }

        if ((deltaX < 0) && (deltaY < 0)) {
            angleInDegrees = 180 - angleInDegrees;
        }

        if ((deltaX > 0) && (deltaY < 0)) {
            angleInDegrees = -angleInDegrees;
        }
        
        angle = convertAngle(angleInDegrees);
    }
    
    
    private GestureAngle convertAngle(float degreesAngle) {
        GestureAngle gestureAngle = GestureAngle.DEG_0;
        
        degreesAngle = degreesAngle+22;
        if (degreesAngle >= 360) {
            degreesAngle = degreesAngle - 360; 
        }
        if (degreesAngle < 0) {
            degreesAngle = 360 + degreesAngle; 
        }
        
        int index = (int) degreesAngle / 45;
        switch (index) {
            case 0:
                gestureAngle = GestureAngle.DEG_0;
                break;
            case 1:
                gestureAngle = GestureAngle.DEG_45;
                break;
            case 2:
                gestureAngle = GestureAngle.DEG_90;
                break;
            case 3:
                gestureAngle = GestureAngle.DEG_135;
                break;
            case 4:
                gestureAngle = GestureAngle.DEG_180;
                break;
            case 5:
                gestureAngle = GestureAngle.DEG_225;
                break;
            case 6:
                gestureAngle = GestureAngle.DEG_270;
                break;
            case 7:
                gestureAngle = GestureAngle.DEG_315;
                break;
        }
        
        
        return gestureAngle;
        
    }
    
    
}
